package com.suray.socket.system;

import com.suray.basic.wcs.utils.LoggerType;
import com.suray.basic.wcs.utils.LoggerUtil;
import com.suray.basic.wcs.utils.ModuleType;
import com.suray.basic.wcs.utils.WcsFuncUtil;
import com.suray.basic.wcs.utils.thread.BaseThread;
import com.suray.socket.SocketInterface;
import com.suray.socket.core.NetAddress;
import com.suray.socket.core.SocketInstance;
import com.suray.socket.system.netty.client.EchoClient;
import com.suray.socket.type.SocketType;

import java.io.IOException;
import java.util.Arrays;

public class SocketImpl extends BaseThread implements SocketInterface {

    protected NetAddress netAddress;
    EchoClient client;
    boolean ioException;

    protected SocketImpl(NetAddress netAddress, SocketType type) {
        super(netAddress.toString() + "通讯", 5000, ModuleType.SOCKET);
        CheckNetAddress(netAddress);
        this.netAddress = netAddress;
        client = new EchoClient(netAddress.getIp(), netAddress.getPort());
        ioException = false;
        LoggerUtil.info(ModuleType.SOCKET, LoggerType.INFO, 0, null,
                netAddress + " 创建连接：" + type, this.getClass());
    }

    private void CheckNetAddress(NetAddress netAddress) {
        SocketInstance.CheckNetAddress(netAddress);
    }

    @Override
    public void sendData(byte[] data) throws IOException {
        if (ioException) {
            client.clearBuffer();
        }

        client.sendData(data);
        ioException = false;
    }

    @Override
    public byte[] recData() {
        byte[] data = client.recData();
        LoggerUtil.debug(ModuleType.SOCKET, LoggerType.INFO, 0, null,
                netAddress + "获取数据：" + WcsFuncUtil.changeToHexString(data), this.getClass());
        return data;
    }

    @Override
    public byte[] recData(int time) throws IOException {
        try {
            byte[] data;
            int tick = 0;
            time /= 10;
            while ((data = client.recData()) == null) {
                if (tick++ >= time) {
                    throw new IOException("接收数据超时：" + netAddress);
                }
                WcsFuncUtil.delay(10);
            }
            LoggerUtil.debug(ModuleType.SOCKET, LoggerType.INFO, 0, null,
                    netAddress + "获取数据：" + Arrays.toString(data), this.getClass());
            return data;
        } catch (IOException e) {
            ioException = true;
            throw e;
        }
    }

    @Override
    public boolean isOnline() {
        return client.isOnline();
    }

    @Override
    public boolean close() {
        this.endThread();
        client.close();
        return true;
    }

    @Override
    protected void process() {
        try {
            client.start();
        } catch (Exception e) {
            WcsFuncUtil.exceptionLog(e, this.getClass());
        }
    }

    @Override
    public String toString() {
        return "SocketImpl{" +
                "netAddress=" + netAddress +
                '}';
    }
}
